import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable, {ActionType, ProColumns} from '@ant-design/pro-table';
import {Button, message, Popconfirm, Space, Tooltip} from 'antd';
import {EditOutlined, PlayCircleOutlined, PlusOutlined} from '@ant-design/icons';
import CreateOrEditForm from './components/CreateOrEditForm';
import JobStatusSwitch from './components/JobStatusSwitch';
import OperationButtons from './components/OperationButtons';
import {API} from "@/services/typings";
import {deleteSysJob, pageSysJob, runJobSAPI} from "@/pages/job/job-manager/service";
import {DeleteOutline} from "antd-mobile-icons";

const JobManagement: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.ISysJob>();
  const [formType, setFormType] = useState<'create' | 'edit'>('create');

  // 表格列配置
  const columns: ProColumns<API.ISysJob>[] = [
    {
      title: '任务名称',
      dataIndex: 'jobName',
      ellipsis: true,
    },
    {
      title: '任务组',
      dataIndex: 'jobGroup',
      valueEnum: {
        'DEFAULT': {text: '默认'},
        'SYSTEM': {text: '系统'},
      },
    },
    {
      title: '调用目标',
      dataIndex: 'invokeTarget',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: 'Cron表达式',
      dataIndex: 'cronExpression',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_, record) => <JobStatusSwitch record={record} tableRef={actionRef}/>,
      valueEnum: {
        '0': {text: '正常', status: 'Success'},
        '1': {text: '暂停', status: 'Error'},
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      align: 'center',
      hideInSearch: true,
      render: (_, record) => <Space size={0}>
        <Tooltip title="编辑定时任务">
          <Button
            onClick={() => {
              setCurrentRow(record);
              setFormType('edit');
              setModalVisible(true);
            }}
            type={'link'}
            size={"small"}>
            <EditOutlined/>
          </Button>
        </Tooltip>
        <Tooltip title="执行一次任务">
          <Button
            onClick={async () => {
              if (!record.jobId) {
                message.error('参数错误')
                return
              }
              const {data} = await runJobSAPI({jobId: record.jobId})
              if (data){
                message.success('执行成功');
              }
            }}
            type={'link'}
            size={"small"}>
            <PlayCircleOutlined/>
          </Button>
        </Tooltip>
        <Tooltip title="删除定时任务">
          <Popconfirm
            title={"确认删除该定时任务嘛？"}
            onConfirm={async () => {
              if (!record.jobId) {
                message.error('参数错误')
                return
              }
              const {data} = await deleteSysJob(record.jobId)
              if (data) {
                message.success('删除成功');
                actionRef.current?.reload()
              }
            }}
          >
            <Button
              type={'link'}
              danger
              size={"small"}>
              <DeleteOutline/>
            </Button>
          </Popconfirm>
        </Tooltip>

      </Space>,
    },
  ];

  return (
    <div>
      <ProTable<API.ISysJob>
        actionRef={actionRef}
        rowKey="jobId"
        columns={columns}
        request={async (params) => {
          const {data} = await pageSysJob(params)
          return data
        }}
        search={{
          span: 6,
        }}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            onClick={() => {
              setCurrentRow(undefined);
              setFormType('create');
              setModalVisible(true);
            }}
          >
            <PlusOutlined/> 新建任务
          </Button>,
        ]}
      />

      <CreateOrEditForm
        visible={modalVisible}
        onVisibleChange={setModalVisible}
        formType={formType}
        currentRow={currentRow}
        onSuccess={() => {
          actionRef.current?.reload()
          setCurrentRow(undefined)
          setModalVisible(false)
        }}
      />
    </div>
  );
};

export default JobManagement;
